package com.zzyl.nursing.service.impl;

import java.beans.Expression;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author wgy
 * @date 2025-01-09
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.判断老人是否已经入住
        //根据老人的身份证和状态查询
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().
                eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo())
                .eq(Elder::getStatus, 1));
        //如果老人已经入住则抛出异常
        if (ObjectUtils.isNotEmpty(elder)) {
            throw new BaseException("老人已经入住");
        }

        //2.更改床位为已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getRoomId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        //3.新增入住老人
        elder = insertOrUpdateElder(bed, checkInApplyDto);

        //4.新增入住老人家属
        //TODO 批量新增家属信息

        //5.新增签约信息
        String contractNumber = "HT" + CodeGenerator.generateContractNumber();
        insertContract(contractNumber, elder, checkInApplyDto);

        //6.新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);

        //7.新增入住配置
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);
    }

    /**
     * 新增入住配置
     * @param id
     * @param checkInApplyDto
     */
    private void insertCheckInConfig(Long id, CheckInApplyDto checkInApplyDto) {
        //创建入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        //添加入住配置，入住表id
        checkInConfig.setCheckInId(id);
        //拷贝其他属性
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        //新增入住配置
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     * @param elder
     * @param checkInApplyDto
     * @return
     */
    public CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        //创建入住信息
        CheckIn checkIn = new CheckIn();
        //给入住信息赋值
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(1);
        //添加入住备注为家人信息
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约信息 合同
     * @param contractNumber
     * @param elder
     * @param checkInApplyDto
     */
    private void insertContract(String contractNumber, Elder elder, CheckInApplyDto checkInApplyDto) {
        //创建签约信息
        Contract contract = new Contract();
        //拷贝签约信息
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        //设置签约编号
        contract.setContractNumber(contractNumber);
        //设置老人的信息
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        //设置生效时间，并根据生效时间判断合同的状态
        LocalDateTime startDate = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime endDate = checkInApplyDto.getCheckInConfigDto().getEndDate();
        contract.setStartDate(startDate);
        contract.setEndDate(endDate);
        contract.setStatus(startDate.isAfter(LocalDateTime.now()) ? 1 : 0);
        //新增签约信息
        contractMapper.insertContract(contract);
    }

    /**
     * 新增或修改老人
     * @param bed
     * @param checkInApplyDto
     * @return
     */
    private Elder insertOrUpdateElder(Bed bed, CheckInApplyDto checkInApplyDto) {
        //创建老人对象
        Elder elder = new Elder();
        //拷贝属性
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(1);
        BeanUtils.copyProperties(checkInApplyDto.getCheckInElderDto(), elder);
        //查询老人信息
        Elder elderDB = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, checkInApplyDto.getCheckInElderDto().getIdCardNo()));

        //判断查询的老人信息是否为空
        if (ObjectUtils.isNotEmpty(elderDB)) {
            //不为空，更新老人信息
            elderMapper.updateById(elder);
        } else {
            //为空，新增老人信息
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 根据入住id查询详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        //查询老人信息
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getId, checkIn.getElderId()));
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        //老人年龄计算
        Period age = Period.between(LocalDate.parse(elder.getBirthday(), DateTimeFormatter.ofPattern("yyyy-MM-dd")), LocalDate.now());
        checkInElderVo.setAge(age.getYears());
        BeanUtils.copyProperties(elder, checkInElderVo);

        //查询老人家属信息
        //TODO 批量查询

        //查询入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);

        //查询签约信息
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId, elder.getId()));

        //创建vo对象，封装查询的数据
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class));
        return checkInDetailVo;
    }
}
